package com.bjpowernode.payment01.web.controller;

import com.bjpowernode.payment01.web.models.dto.NoticeResultDto;
import com.bjpowernode.payment01.web.models.dto.PaymentDto;
import com.bjpowernode.payment01.web.models.form.GoodsForm;
import com.bjpowernode.payment01.web.models.form.NoticeForm;
import com.bjpowernode.payment01.web.service.PaymentService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class OrderController {
    @Resource
    PaymentService paymentService;
    @RequestMapping("/order/buy")
    public String buy(GoodsForm goodsForm, Model model){
        PaymentDto paymentDto = paymentService.generateParamSaveOrder(goodsForm);
        model.addAttribute("pay",paymentDto);
        return "confirm";
    }
    //接收异步通知
    @RequestMapping("/notice/kq")
    @ResponseBody
    public String notice(NoticeForm noticeForm){
        String pageUrl= "http://localhost:8080/show.html";
        String returnTemplate = "<result>%d</result> <redirecturl>%s</redirecturl>";
        //1接收异步通知
        try{
            boolean flag = noticeForm.checkSign();
            System.out.println("验证签名:" + flag);
            //测试使用
            flag = true;
            if (!flag) {
                throw new RuntimeException("签名验证失败");
            }
            //处理业务逻辑
            NoticeResultDto noticeResultDto = paymentService.handleNotice(noticeForm);
            //2应答字符串
            String result = noticeResultDto.getResult();
            pageUrl = noticeResultDto.getPageUrl();
            if ("FAIL".equals(result)) {//需要重发
                return String.format(returnTemplate, 0, pageUrl);
            }
        }catch (Exception e){
            e.printStackTrace();
            return String.format(returnTemplate,0,pageUrl);
        }
        return String.format(returnTemplate,1,pageUrl);
    }
}
